//
//  VGBaseChoiceView.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/7/13.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//  选择控件 2.0版

import UIKit


/// 选择控件view基础类
class VGBaseChoiceView<M: Codable, C: VGBaseChoiceCell<M>>: UIView, UITableViewDelegate, UITableViewDataSource {
    
    fileprivate var dataSource: [VGBaseChoiceModel<M>] = [VGBaseChoiceModel<M>]()
    
    fileprivate var choiceType: BaseChoiceType!
    
    // row高度 为0时->自适应高度
    public var tableViewRowHeight: CGFloat = 45
    
    public var selectRowClosure: ((Int)->Void)?
    
    public var cancelClosure: (()->Void)?
    
    public var tableView: UITableView!
    
    public var bottomBt: UIButton!

    public var unSelectedIndex:Int?//不能选中该项
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        showSelf(false)
        self.setupTableView()
        self.setupBottomBt()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 外部控制显示 内部控制隐藏
    public func showSelf(_ show: Bool) {
        self.isHidden = !show
    }
    
    @objc public func hideView() {
        self.isHidden = true
        self.cancelClosure?()
    }
    
    public func setDataSource(_ data: [VGBaseChoiceModel<M>], _ type: BaseChoiceType = .normalCancel) {
        
        self.dataSource = data
        self.choiceType = type
        self.configDataSource()
        self.updateTableViewConstraints()
        self.tableView.reloadData()
    }
    
    fileprivate func setupTableView() {
        
        tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.bounces = false
        tableView.register(C.self, forCellReuseIdentifier: NSStringFromClass(C.self))
        tableView.delegate = self
        tableView.dataSource = self
        self.addSubview(self.tableView)
    }
    
    fileprivate func setupBottomBt() {
        
        bottomBt = UIButton(frame: CGRect.zero)
        bottomBt.backgroundColor = UIColor(white: 0, alpha: 0.5)//UIColor(r: 0, g: 0, b: 0, a: 0.4)
        bottomBt.addTarget(self, action: #selector(hideView), for: .touchUpInside)
        self.addSubview(self.bottomBt)
    }
    
    // 如果是取消 则加上灰色分割和取消cell
    fileprivate func configDataSource() {
        
        switch choiceType {
        case .normalCancel?:
            // 灰条 取消cell的数据
            let m: VGBaseChoiceModel<M> = VGBaseChoiceModel<M>()
            m.cellType = .graySep
            m.isSelected = false
            let cm: VGBaseChoiceModel<M> = VGBaseChoiceModel<M>()
            cm.cellType = .cancel
            m.isSelected = false
            self.dataSource.append(m)
            self.dataSource.append(cm)
        default:
            break
        }
    }
    
    public func updateTableViewConstraints() {
        
        var tableViewHeight: CGFloat = 0.0
        
        if choiceType == .noBottom {
            
            tableViewHeight = self.frame.size.height
        } else {
            
            if choiceType == .normalCancel {
                
                tableViewHeight = CGFloat(dataSource.count - 1) * tableViewRowHeight + 10
            } else  {
                
                tableViewHeight = CGFloat(dataSource.count) * tableViewRowHeight
            }
            
            if tableViewHeight > self.frame.size.height - 200 {
                tableViewHeight = self.frame.size.height - 200
            }
        }
        
        self.tableView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(tableViewHeight)
        }
        
        self.bottomBt.snp.makeConstraints { (make) in
            make.top.equalTo(self.tableView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(SCREEN_HEIGHT)
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        // 如果不是取消、也不是取消上面的灰条
        if let m = dataSource.objectAtIndex(index: indexPath.row) {
            if m.canEdit == false {
                return
            }
            
            if m.cellType == .normal {

                if let unSelectedIndex = unSelectedIndex,unSelectedIndex == indexPath.row{
                    m.isSelected = false
                }else{
                    let _ = dataSource.map { $0.isSelected = false }
                    m.isSelected = true
                }

                tableView.reloadData()
                
                if let closure = selectRowClosure
                {
                    closure(indexPath.row)
                }
            }
        }
        
        // 没有底部蒙层 点击不隐藏
        if choiceType != .noBottom {
            showSelf(false)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        // 如果是灰条
        if indexPath.row == dataSource.count - 2 && choiceType == .normalCancel {
            return 10
        } else if tableViewRowHeight == 0 {
            return UITableView.automaticDimension
        } else {
            return tableViewRowHeight
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell: C? = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(C.self)) as? C
        if cell == nil {
            cell = C(style: .default, reuseIdentifier: NSStringFromClass(C.self))
        }
        if let m = self.dataSource.objectAtIndex(index: indexPath.row) {
            cell?.configCell(m, indexPath, self.dataSource)
        }
        cell?.selectionStyle = .none
        return cell!
    }
}

